<template>
  <div>
    <a-card title="订单详情" :bordered="false">
      <template #extra>
        <a-space>
          <a-button
            v-if="allowOperation.editPrice"
            type="outline"
            @click="modifyPrice"
            >调整价格</a-button
          >
          <a-button
            v-if="allowOperation.editConsignee"
            type="outline"
            @click="editAddress"
            >修改收货地址</a-button
          >
          <a-button
            v-if="allowOperation.take"
            type="outline"
            @click="orderTakes"
            >订单核销</a-button
          >
          <!--<a-button-->
            <!--v-if="allowOperation.ship"-->
            <!--class="mr-10"-->
            <!--type="primary"-->
            <!--@click="orderDeliverModal = true"-->
            <!--&gt;发货</a-button-->
          <!--&gt;-->
          <a-button
            v-if="allowOperation.ship"
            type="primary"
            @click="groupShipModal = true"
            >发货</a-button
          >
          <a-button
            v-if="allowOperation.ship && packageTraceList.length === 0"
            type="primary"
            @click="openSheetModal"
            >电子面单</a-button
          >
          <a-button
            v-print="printInfoObj"
            type="outline"
            >打印发货单</a-button
          >
          <a-button @click="back()">返回</a-button>
        </a-space>
      </template>
      <a-steps :current="current" line-less style="padding: 30px 200px 0 200px" v-if="orderInfo.order.orderStatus !== 'CANCELLED'">
        <a-step>买家下单</a-step>
        <a-step>付款成功</a-step>
        <a-step>
          <span v-if="orderInfo.order.orderType == 'VIRTUAL'">待使用</span>
          <span v-if="orderInfo.order.deliveryMethod == 'SELF_PICK_UP'">待自提</span>
          <span v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod === 'LOGISTICS'">商家发货</span>
        </a-step>
        <a-step v-if="orderInfo.order.orderType === 'NORMAL' && orderInfo.order.deliveryMethod === 'LOGISTICS'">用户收货</a-step>
        <a-step>交易完成</a-step>
      </a-steps>
      <a-steps :current="4" line-less style="padding: 30px 200px 0 200px" v-if="orderInfo.order.orderStatus === 'CANCELLED'">
        <a-step>提交申请</a-step>
        <a-step>取消处理</a-step>
        <a-step>审核通过</a-step>
        <a-step>完成</a-step>
      </a-steps>
    </a-card>
    <a-card
      title="订单信息"
      :bordered="false"
      style="margin-bottom: 0; padding-bottom: 0"
    >
      <a-row :gutter="24" class="grid-row">
        <a-col :span="8">
          <div
            >订单编号：<span>{{ orderInfo.order.sn }}</span></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >支付方式：<span>{{ orderInfo.paymentMethodValue }}</span></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >下单时间：<span>{{ orderInfo.order.createTime }}</span></div
          >
        </a-col>
      </a-row>
      <a-row :gutter="24" class="grid-row">
        <a-col :span="8">
          <div
            >订单来源：<span>{{ orderInfo.order.clientType }}</span></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >付款状态：<span>{{ orderInfo.payStatusValue }}</span></div
          >
        </a-col>
        <a-col :span="8" v-if="orderInfo.order.orderType !== 'VIRTUAL'">
          <div
            >配送方式：<span>{{ orderInfo.deliveryMethodValue }}</span></div
          >
        </a-col>
      </a-row>
      <a-row :gutter="24" class="grid-row">
        <a-col :span="8">
          <div
            >订单状态：<span>{{ orderInfo.orderStatusValue }}</span></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >支付单号：<span>{{ orderInfo.order.tradeSn }}</span></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >完成时间：<span>{{ orderInfo.order.completeTime }}</span></div
          >
        </a-col>
      </a-row>
      <a-row :gutter="24"
       v-if="(orderInfo.order.deliveryMethod == 'SELF_PICK_UP')"
        class="grid-row"
      >
        <a-col :span="24">自提信息：<span>{{ orderInfo.order.storeAddressPath }}</span><span style="margin-left: 40px;margin-top: 25px">{{ orderInfo.order.storeAddressMobile }}</span></a-col>

      </a-row>
    </a-card>
    <a-card
        v-if="(orderInfo.order.deliveryMethod != 'SELF_PICK_UP' &&orderInfo.order.orderType != 'VIRTUAL')"
      title="收货信息"
      :bordered="false"
      style="margin: 0; padding-bottom: 0; padding-top: 0px"
    >
      <a-row :gutter="24" class="grid-row">
        <a-col :span="8">
          <div
            >收货人：<span>{{ orderInfo.order.consigneeName }}</span></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >联系方式：<span>{{ orderInfo.order.consigneeMobile }}</span></div
          >
        </a-col>
      </a-row>
      <a-row :gutter="24" class="grid-row">
        <a-col :span="8">
          <div
            >收货地址：<span
              >{{ orderInfo.order.consigneeAddressPath
              }}{{ orderInfo.order.consigneeDetail }}</span
            ></div
          >
        </a-col>
        <a-col :span="8">
          <div
            >用户留言：<span>{{ orderInfo.order.remark }}</span></div
          >
        </a-col>
      </a-row>
    </a-card>
    <a-card
        v-if="(orderInfo.order.deliveryMethod != 'SELF_PICK_UP'
        &&orderInfo.order.orderType != 'VIRTUAL'
        &&orderInfo.order.deliverStatus!='UNDELIVERED')"
      title="查询物流"
      :bordered="false"
    >
      <tablePage
        ref="logisticsRef"
        :columns="columnLogisticsTable"
        :enable-pagination="false"
        :bordered="true"
        :methods="sortLogisticsMethods"
        :data-list="logisticsList"
        v-if="logisticsList && logisticsList.length"
      >
        <template #goodsName="{ data }">
          <div v-for="(item, index) in data.orderPackageItemList" :key="index">
            <a-image width="50" height="50" :src="item.thumbnail" show-loader>
              <template #loader> <div class="loader-animate" /></template
            ></a-image>
            <a href="javascript:;" style="text-decoration: none">
              {{ item.goodsName }}</a
            >
          </div>
        </template>
        <template #options="{ record, rowIndex }"><a-button type="text" @click="checkLogisticsDetail(record, rowIndex)">查看</a-button></template>
      </tablePage>

      <div v-else>
        <a-button class="mr-10" type="primary" @click="logisticsModal = true">查询物流</a-button>
      </div>

    </a-card>
<!--    <a-card title="售后记录" :bordered="false">-->
<!--      <tablePage-->
<!--        ref="afterSaleRef"-->
<!--        :columns="columnAfterSaleTable"-->
<!--        :enable-pagination="false"-->
<!--        :bordered="true"-->
<!--        :methods="sortAfterSaleMethods"-->
<!--      ></tablePage>-->
<!--    </a-card>-->
    <a-card title="订单日志" :bordered="false">
      <tablePage
        ref="logRef"
        :columns="columnSorderLogTable"
        :data-list="orderInfo.orderLogs"
        :enable-pagination="false"
        :bordered="true"
      >
        <template #messageSlot="{ record }">
          <div style="text-wrap: wrap"> {{ record }} </div>
        </template>
      </tablePage>
    </a-card>
    <a-card title="订单货物" :bordered="false">
      <tablePage
        ref="goodsRef"
        :columns="columnGoodsTable"
        :enable-pagination="false"
        :bordered="true"
        :data-list="data"
      >
        <template #discounts="{ data }">
          <div v-if="data.priceDetailDTO && data.priceDetailDTO.discountPriceDetail">
            <div v-for="discount in data.priceDetailDTO.discountPriceDetail">
              <a-tag mb-2>{{ discount.promotionName }}</a-tag>
            </div>
          </div>
          <div v-else>暂未参加任何促销活动</div>
        </template>
      </tablePage>
    </a-card>
    <div class="footer">
      <div class="footer-font"
        >应付：<span class="">{{
          unitPrice(orderInfo.order.priceDetailDTO.flowPrice, '¥')
        }}</span></div
      >
      <div
        >优惠：<span>{{
          unitPrice(orderInfo.order.priceDetailDTO.discountPrice, '¥')
        }}</span></div
      >
      <div
        >优惠券：<span>-{{
          unitPrice(orderInfo.order.priceDetailDTO.couponPrice, '¥')
        }}</span></div
      >
      <div
        >运费：<span>{{
          unitPrice(orderInfo.order.freightPrice, '￥')
        }}</span></div
      >
      <div
        >商品总价:<span>{{
          unitPrice(orderInfo.order.priceDetailDTO.goodsPrice, '￥')
        }}</span></div
      >
    </div>
    <!-- 订单核销 -->
    <a-modal v-model:visible="orderTakeModal" width="500px" title="核销订单">
      <a-form
        ref="formRef"
        :model="orderTakeForm"
        :style="{ width: '460px' }"
        layout="horizontal"
        auto-label-width
      >
        <a-form-item field="qrCode" label="核销码" :rules="[REQUIRED]">
          <a-input v-model="orderTakeForm.qrCode"></a-input>
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button @click="orderTakeModal = false">取消</a-button>
          <a-button
            style="margin-left: 10px"
            type="primary"
            @click="orderTakeSubmit"
            >确认</a-button
          >
        </div>
      </template>
    </a-modal>
    <!-- 修改发货地址 -->
    <a-modal
      v-model:visible="editAddressModal"
      width="630px"
      title="修改收件信息"
    >
      <div>
        <a-form
          ref="formRef"
          :model="addressForm"
          :style="{ width: '460px' }"
          layout="horizontal"
          auto-label-width
        >
          <a-form-item
            field="consigneeName"
            label="收件人"
            :rules="[REQUIRED, VARCHAR20]"
          >
            <a-input v-model="addressForm.consigneeName" />
          </a-form-item>
          <a-form-item
            field="consigneeMobile"
            label="联系方式"
            :rules="[REQUIRED, VARCHAR20]"
          >
            <a-input v-model="addressForm.consigneeMobile" />
          </a-form-item>
          <a-form-item
            field="consigneeAddressPath"
            label="地址信息"
            :rules="[REQUIRED]"
          >
            <a-input
              v-if="showRegion"
              v-model="addressForm.consigneeAddressPath"
              disabled
            />
            <a-button v-if="showRegion" type="primary" @click="regionClick"
              ><icon-edit />修改</a-button
            >
            <city
              v-if="showCity"
              :key="isShowCity"
              :ids="addressInformation"
              :address="addressForm.consigneeAddressPath"
              @callback="cityRes"
            />
          </a-form-item>
          <a-form-item
            field="consigneeDetail"
            label="详细地址"
            :rules="[REQUIRED]"
          >
            <a-input v-model="addressForm.consigneeDetail" />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button @click="handleCancel">取消</a-button>
          <a-button style="margin-left: 10px" type="primary" @click="handleOk"
            >修改</a-button
          >
        </div>
      </template>
    </a-modal>
    <!-- 打印发货单 -->
    <a-modal v-model:visible="printModal" width="500px">
      <div style="max-height: 500px; overflow-y: auto; overflow-x: hidden;">
        <div id="printInfo" style="padding: 20px;box-sizing: border-box;">
          <!-- <a-row :gutter="24">
            <a-image width="100" :src="storeSideLogo"></a-image></a-row> -->
          <a-row :gutter="24" style="font-size: 20px; margin: 5px 0; font-weight: 600">订单{{ orderInfo.order.sn}}<a-tag style="margin-left: 10px">{{orderInfo.orderStatusValue}}</a-tag></a-row>
          <a-row :gutter="24" style="margin-top: 20px;margin-left: 0;">创建时间 ：{{ orderInfo.order.createTime }}</a-row>
          <div class="print-good-title">商品信息：</div>
          <a-table :columns="printGoodsColumns" :data="orderInfo.orderItems" :pagination="false"></a-table>
          <div class="print-good-title">订单信息：</div>
          <a-row :gutter="24">
            <a-table :columns="printOrderColumns" :data="orderInfo.orderItems" :pagination="false">
              <template #consigneeAddressPath="{}">
                <p>{{ orderInfo.order.consigneeName }} {{ orderInfo.order.consigneeMobile }} {{ orderInfo.order.consigneeAddressPath }} {{ orderInfo.order.consigneeDetail }}</p>
              </template>
              <template #deliveryMethodValue="{}"><p>{{ orderInfo.deliveryMethodValue }}</p></template>
              <template #paymentMethodValue="{}"><p>{{ orderInfo.paymentMethodValue }}</p></template>
            </a-table>
          </a-row>
          <!-- <div class="printFooter">
            <p><a-image width="100" :src="storeSideLogo" style="margin-left: 45%"></a-image></p>
            <p>{{config.company.name}}</p>
            <p>备案号：{{config.icpMessage}}</p>
          </div> -->
        </div>
      </div>
    </a-modal>
    <!-- 发货物流模态框 -->
    <a-modal
      v-model:visible="orderDeliverModal"
      ref="deliverRef"
      width="500px"
      title="订单发货"
      ok-text="发货"
      @ok="orderDeliverySubmit"
    >
      <div class="layui-layer-wrap">
        <a-form
          :model="orderDeliveryForm"
          :style="{ width: '460px' }"
          layout="horizontal"
          auto-label-width
        >
          <a-form-item field="logisticsId" label="物流公司" :rules="[REQUIRED]">
            <a-select
              v-model="orderDeliveryForm.logisticsId"
              :style="{ width: '320px' }"
              placeholder="请选择物流公司"
              allow-clear
            >
              <a-option
                v-for="(item, i) in checkedLogistics"
                :key="i"
                :value="item.logisticsId"
                >{{ item.name }}</a-option
              >
            </a-select>
          </a-form-item>
          <a-form-item v-if="!facesheetFlag" field="logisticsNo" label="物流单号" :rules="[REQUIRED]">
            <a-input
              v-model="orderDeliveryForm.logisticsNo"
              :style="{ width: '320px' }"
            ></a-input>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <!-- 分包裹发货 -->
    <a-modal v-model:visible="groupShipModal" width="900px">
      <template #title>发货</template>
      <div class="layui-layer-wrap">
        <a-form ref="formRef" :model="groupOrderDeliveryForm" :style="{ width: '460px' }" layout="horizontal" auto-label-width>
          <a-form-item field="logisticsId" label="物流公司" :rules="[REQUIRED]">
            <a-select v-model="groupOrderDeliveryForm.logisticsId" :style="{ width: '320px' }" placeholder="请选择物流公司" allow-clear>
              <a-option v-for="(item, i) in checkedLogistics" :key="i" :value="item.logisticsId">{{ item.name }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="logisticsNo" label="物流单号" :rules="[REQUIRED]">
            <a-input v-model="groupOrderDeliveryForm.logisticsNo" :style="{ width: '320px' }"></a-input>
          </a-form-item>
        </a-form>
        <tablePage ref="groupShipRef" :columns="groupShipColumns" :data-list="data" :enable-pagination="false" :bordered="true" :checkbox="true" @selectionChanges="(val) => {selectedKeys = val;}">
          <template #num="{ rowIndex }">
            <a-input-number v-model="data[rowIndex].canNum" :style="{ width: '160px' }" class="input-demo" :min="0" :max="data[rowIndex].___num - data[rowIndex].deliverNumber"/>
          </template>
        </tablePage>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button @click="groupShipModal = false">取消</a-button>
          <a-button style="margin-left: 10px" type="primary" @click="confirmShipGroupGoods">发货</a-button>
        </div>
      </template>
    </a-modal>
    <!-- 调整价格 -->
    <a-modal v-model:visible="adjustmentPrice" width="500px" title="修改金额">
      <div>
        <a-form
          ref="modifyPriceForm"
          :model="modifyPriceForm"
          :style="{ width: '460px' }"
          layout="horizontal"
          auto-label-width
        >
          <a-form-item field="reason" label="订单金额">
            <a-input-number
              v-model="modifyPriceForm.price"
              :style="{ width: '320px' }"
              class="input-demo"
              :min="0"
              :max="999999"
            />
            <span class="ml_10">元</span>
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button @click="adjustmentPrice = false">关闭</a-button>
          <a-button
            style="margin-left: 10px"
            type="primary"
            status="danger"
            @click="modifyPriceSubmit"
            >调整</a-button
          >
        </div>
      </template>
    </a-modal>

    <!--查询物流modal-->
    <a-modal v-model:visible="logisticsModal" width="600px">
      <template #title>查询物流</template>
      <div class="wuliu">
        <template v-if="packageTraceList.length > 0" v-for="(packageItem, packageIndex) in packageTraceList" :key="packageIndex">
          <div class="layui-layer-wrap">
            <div class="flex"><div>物流公司：</div><div>{{ packageItem.logisticsName }}</div></div>
            <div class="flex"><div>快递单号：</div><div>{{ packageItem.logisticsNo }}</div></div>
            <div class="div-express-log fontsize-14">
              <ul class="express-log express-log-name">
                <li v-for="(item, index) in packageItem.orderPackageItemList" :key="index">
                  <span class="time" style="width: 50%;"><span>商品名称：</span><span>{{ item.goodsName }}</span></span>
                  <span class="time" style="width: 30%;"><span>发货时间：</span><span>{{ item.logisticsTime }}</span></span>
                  <span class="time" style="width: 20%;"><span>发货数量：</span><span>{{ item.deliverNumber }}</span></span>
                </li>
              </ul>
              <div class="div-express-log" style="overflow: hidden;">
                <ul class="express-log" v-if="packageItem.traces && packageItem.traces.traces">
                  <li v-for="(item, index) in packageItem.traces.traces" :key="index">
                    <span class="time">{{ item.AcceptTime || item.acceptTime }}</span>
                    <span class="detail">{{ item.AcceptStation || item.remark }}</span>
                  </li>
                </ul>
                <ul class="express-log" v-else><li>暂无物流信息</li></ul>
              </div>
            </div>
          </div>
        </template>
        <template v-if = "packageTraceList.length === 0 && logisticsInfo">
          <div class="layui-layer-wrap">
            <div class="flex"><div>物流公司：</div><div>{{ logisticsInfo.shipper }}</div></div>
            <div class="flex"><div>快递单号：</div><div>{{ logisticsInfo.logisticCode }}</div></div>
            <div class="div-express-log">
            <ul class="express-log" v-if="logisticsInfo && logisticsInfo.traces">
              <li v-for="(item, index) in logisticsInfo.traces" :key="index">
                <span class="time">{{ item.AcceptTime }}</span>
                <span class="detail">{{ item.AcceptStation }}</span>
              </li>
            </ul>
            <ul class="express-log" v-else><li>暂无物流信息</li></ul>
            </div>
          </div>
        </template>
      </div>
      <template #footer>
        <a-button @click="logisticsModal = false">取消</a-button>
      </template>
    </a-modal>

    <a-modal v-model:visible="modalPrint" style="height:300px;" @on-ok="printOk" @on-cancel="printNo">
      <div id="printContent" style="line-height:24px;padding: 10px;" v-html="printSheetData"></div>
    </a-modal>


  </div>
</template>

<script lang="ts" setup>
  import {
editOrderConsignee,
getLogisticsChecked,
getPackage,
getTraces,
orderDelivery,
orderDetail,
orderTake,
partDelivery,
updateOrderPrice,
getOrderFaceSheet
} from '@/api/order';
import city from '@/components/m-city/index.vue';
import tablePage from '@/components/table-pages/index.vue';
import { ColumnsDataRule, MethodsRule } from '@/types/global';
import { unitPrice } from '@/utils/filters';
import { REQUIRED, VARCHAR20 } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, reactive, ref, inject } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getCheckedOn } from '@/api/logistics';
import {
addressFormRule,
modifyPriceFormRule,
orderTakeFormRule,
} from './type';
import config from '@/config/index';

const storeSideLogo = ref<any>(
    localStorage.getItem('seller_logo')
  );

  const deliverRef = ref<any>();
  const reload: any = inject("reload");
  const current = ref(1);
  const route = useRoute();
  const router = useRouter();
  const isShowCity = ref(1);
  const data = ref<any>([]); // 表单数据
  const formRef = ref<FormInstance>(); // 表单
  const orderStatusValue = ref(''); // 订单状态
  const orderCancelModal = ref<boolean>(false); // 订单取消
  const orderTakeModal = ref<boolean>(false); // 订单核销
  const facesheetFlag = ref<boolean>(false);
  const modalPrint = ref<boolean>(false);
  const printSheetData = ref<String>("");
  const printModal = ref<boolean>(false); // 打印发货单弹框是否开启
  const orderDeliverModal = ref<boolean>(false); // 发货物流模态框
  const editAddressModal = ref<boolean>(false); // 修改收货地址
  const adjustmentPrice = ref<boolean>(false); // 调整价格弹框是否开启
  const groupShipModal = ref<boolean>(false); // 分包裹发货
  const allowOperation = ref({}) as any; // 订单可才做选项
  const orderInfo = ref({ order: { priceDetailDTO: {} } }) as any;
  const logisticsList = ref<any>([]); // 查询物流
  const checkedLogistics = ref<any>({}); // 物流列表
  const showRegion = ref<boolean>(true);
  const showCity = ref<boolean>(false); // 地址是否显示
  const modifyPriceForm = ref<modifyPriceFormRule>({ price: 0 }); // 调整价格
  const orderDeliveryForm = ref<any>({ logisticsNo: '', logisticsId: '' }); // 物流信息
  const groupOrderDeliveryForm = ref<any>({ logisticsNo: '', logisticsId: '' });
  // 打印
  const printInfoObj = reactive({
    id: 'printInfo', // 要打印的id名 无#号
    popTitle: '&nbsp;', // 页眉标题 默认浏览器标题 空字符串时显示undefined 使用html语言
    extraHead: '', // 头部文字 默认空
  });
  const addressInformation = ref<any>();
  // 修改收件信息（修改按钮）
  const regionClick = () => {
    isShowCity.value += 1;
    showRegion.value = false;
    showCity.value = true;
  };
  const orderTakeForm = ref<orderTakeFormRule>({ qrCode: '' }); // 订单核销
  const addressForm = reactive<addressFormRule>({
    // 修改收货地址
    consigneeName: '',
    consigneeMobile: '',
    consigneeDetail: '',
    consigneeAddressPath: '',
  });
  // 订单日志表头
  const columnSorderLogTable: ColumnsDataRule[] = [
    {
      title: '操作者',
      dataIndex: 'operatorName',
    },
    {
      title: '操作类型',
      dataIndex: 'operatorType',
    },
    {
      title: '时间',
      dataIndex: 'createTime',
    },
    {
      title: '日志',
      dataIndex: 'message',
      width: 600,
      slot: true,
      slotTemplate: 'messageSlot',
    },
  ];
  const groupShipColumns: ColumnsDataRule[] = [
    {
      title: '商品',
      dataIndex: 'goodsName',
      slot: true,
      width: 300,
      ellipsis: false,
      slotData: {
        goods: {
          goodsImage: 'image',
          goodsName: 'goodsName',
        },
      },
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      currency: true,
    },
    {
      title: '数量',
      dataIndex: 'num',
      width: 200,
      slot: true,
      slotTemplate: 'num',
    },
    {
      title: '已发包裹',
      dataIndex: 'deliverNumber',
    },
    {
      title: '小计',
      dataIndex: 'subTotal',
      currency: true,
    },
  ];
  const selectedKeys = ref<any>([]);
  // 物流表头
  const columnLogisticsTable: ColumnsDataRule[] = [
    {
      title: '产品',
      dataIndex: 'goodsName',
      slot: true,
      slotTemplate: 'goodsName',
    },
    {
      title: '物流公司',
      dataIndex: 'logisticsName',
    },
    {
      title: '物流单号',
      dataIndex: 'logisticsNo',
    },
  ];
  // 售后表头
  const columnAfterSaleTable: ColumnsDataRule[] = [
    {
      title: '产品',
      dataIndex: 'operatorName',
    },
    {
      title: '售后类型',
      dataIndex: 'operatorName',
    },
    {
      title: '售后单号',
      dataIndex: 'operatorName',
    },
    {
      title: '状态',
      dataIndex: 'operatorName',
    },
    {
      title: '申请时间',
      dataIndex: 'operatorName',
    },
  ];
  // 订单货物表头
  const columnGoodsTable: ColumnsDataRule[] = [
    {
      title: '产品',
      dataIndex: 'goodsName',
      slot: true,
      width: 300,
      ellipsis: false,
      slotData: {
        goods: {
          goodsImage: 'image',
          goodsName: 'goodsName',
        },
      },
    },
    {
      title: '单价',
      dataIndex: 'goodsPrice',
      currency: true,
    },
    {
      title: '数量',
      dataIndex: 'num',
    },
    {
      title: '商品总价',
      dataIndex: 'subTotal',
      currency: true,
    },
    {
      title: '参与的优惠活动',
      dataIndex: 'promotionType',
      slot: true,
      slotTemplate: 'discounts',
    },
  ];
  const sortLogisticsMethods: MethodsRule = {
    title: '操作',
    width: 100,
    methods: [
      {
        title: '查看',
        callback: 'detail',
        type: 'text',
        slot: true,
        slotTemplate: 'options'
      },
    ],
  };
  const sortAfterSaleMethods: MethodsRule = {
    title: '操作',
    width: 100,
    methods: [
      {
        title: '查看',
        callback: 'detail',
        type: 'text',
      },
    ],
  };
  const printGoodsColumns = ref([
    {
      title: '产品名称',
      dataIndex: 'goodsName',
      width: 500,
    },
    {
      title: '货号',
      dataIndex: 'skuSn',
      width: 200,
    },
    {
      title: '发货数量',
      dataIndex: 'num',
      width: 200,
    },
  ]);
  const printOrderColumns = ref([
    {
      title: '送货地址',
      dataIndex: 'consigneeAddressPath',
      width: 500,
      slotName: 'consigneeAddressPath',
    },
    {
      title: '配送方式',
      dataIndex: 'deliveryMethodValue',
      slotName: 'deliveryMethodValue',
      width: 200,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethodValue',
      slotName: 'paymentMethodValue',
      width: 200,
    },
  ]);
  const logisticsModal = ref(false);
  const packageTraceList = ref<any>([]);
  const logisticsInfo = ref<any>([]);
  // 查询物流
  const checkLogisticsDetail = (row: any, index: number) => {
    logisticsModal.value = true;
    packageTraceList.value = [];
    packageTraceList.value.push(logisticsList.value[index]);
  };

  // 初始化
  const init = () => {
    orderDetail(route.query.id).then((res) => {
      allowOperation.value = res.data.result.allowOperationVO;
      orderInfo.value = res.data.result;
      data.value = res.data.result.orderItems;
      // diaLogKey.value = true
      orderStatusValue.value = orderInfo.value.orderStatusValue;

      if (res.data.result.orderItems.length) {
        data.value = res.data.result.orderItems.map((item: any) => {
          return {
            ...item,
            ___num: item.num,
            _disabled: item.deliverNumber >= item.num,
            canNum: item.num - item.deliverNumber,
          };
        });
      }
      if (orderStatusValue.value) {
        if (orderStatusValue.value == '未付款') {
          current.value = 1;
        } else if (orderStatusValue.value == '已付款') {
          current.value = 2;
        }else if (orderStatusValue.value == '待发货' || orderStatusValue.value == '部分发货' || orderStatusValue.value == '待使用') {
          current.value = 3;
        } else if (orderStatusValue.value === '待收货') {
          current.value = 4;
        }else if (orderStatusValue.value == '已完成') {
          if (orderInfo.value.order.orderType === 'NORMAL' && orderInfo.value.order.deliveryMethod === 'LOGISTICS') {
            current.value = 5;
          } else {
            current.value = 4;
          }
        }
      }
    });
  };
  // 级联子组件传过来的值
  const cityRes = (val: any) => {
    addressInformation.value = val.ids.join(',');
    addressForm.consigneeAddressPath = val.cities.join(',');
  };
  // 订单核销
  const orderTakes = () => {
    orderTakeForm.value.qrCode = orderInfo.value.order.verificationCode;
    orderTakeModal.value = true;
  };
  const openSheetModal =() =>{
    facesheetFlag.value = true;
       getCheckedOn().then(res => {
        if (res.data.success) {
          checkedLogistics.value = res.data.result;
          orderDeliverModal.value = true;
        }
       });
  };
  // 订单核销弹框确认
  const orderTakeSubmit = async () => {
    const auth = await formRef.value?.validate();
    if (!auth) {
      const res = await orderTake(route.query.id, orderTakeForm.value.qrCode);
      if (res.data.code == 200) {
        Message.success('订单核销成功');
        init();
        orderTakeModal.value = false;
      }
    }
  };
  const handleCancel = () => {
    // 修改收货地址关闭事件
    editAddressModal.value = false; // 关闭弹框
    showRegion.value = true;
    showCity.value = false;
  };
  // 修改发货地址确定按钮
  const handleOk = async () => {
    const auth = await formRef.value?.validate();
    if (!auth) {
      const params = {
        ...addressForm,
        consigneeAddressIdPath: addressInformation.value,
      };
      editOrderConsignee(route.query.id, params).then((res: any) => {
        if (res.data.code == 200) {
          Message.success('修改成功！');
          editAddressModal.value = false; // 关闭弹框
          showRegion.value = true;
          showCity.value = false;
          init();
        }
      });
    }
  };
  // 修改收货地址
  const editAddress = () => {
    editAddressModal.value = true;
    if (orderInfo.value.order) {
      const {
        consigneeMobile,
        consigneeDetail,
        consigneeName,
        consigneeAddressPath,
        consigneeAddressIdPath,
      } = orderInfo.value.order;
      addressForm.consigneeMobile = consigneeMobile;
      addressForm.consigneeDetail = consigneeDetail;
      addressForm.consigneeName = consigneeName;
      addressForm.consigneeAddressPath = consigneeAddressPath;
      addressInformation.value = consigneeAddressIdPath;
    }
  };

  // 订单发货提交
  const orderDeliverySubmit = async () => {
    if(facesheetFlag.value){
      const auth = await deliverRef.value?.validate();
      if (!auth) {
        getOrderFaceSheet(route.query.id, orderDeliveryForm.value).then(res => {
          if (res.data.success) {
            printSheetData.value = res.data.result.printTemplate;
            toPrints();
          }
        });
      }
    }else{
      orderDelivery(route.query.id, orderDeliveryForm.value).then((res) => {
        if (res.data.success) {
          Message.success('订单发货成功');
          orderDeliverModal.value = false;
          init();
        }
      });
    }
  };
  const toPrints = async () => {
    orderDeliverModal.value = false;
    modalPrint.value = true;
  };
  const printNo= async () => { //点击拒绝
    modalPrint.value = false;
    init()
  };
  const printOk = async () => {
    const oldStr = window.document.body.innerHTML;
    const newStr = document.getElementById('printContent')!.innerHTML;
    window.document.body.innerHTML = newStr;
    window.print();
    window.document.body.innerHTML = oldStr;
    location.reload();
//  this.getDataDetail();
  };
  // 分包裹发货
  const confirmShipGroupGoods = async () => {
    const auth = await formRef.value?.validate();
    if (!auth) {
      if (selectedKeys.value && selectedKeys.value.length) {
        const submit = {
          ...groupOrderDeliveryForm.value,
          orderSn: route.query.id,
          partDeliveryDTOList: data.value.filter((i: any) =>selectedKeys.value.includes(i.id)).map((item: any) => {
            return {orderItemId: item.id, deliveryNum: item.canNum};
          }),
        };
        let result = true;
        submit.partDeliveryDTOList.map((item: any) => {
          if (Number(item.deliveryNum) <= 0) {
            Message.warning('商品发货数量不能为0');
            result = false;
            return;
          }
        });
        if (result) {
          partDelivery(route.query.id, submit).then((res: any) => {
            if (res.data.success) {
              Message.success('发货成功!');
              groupShipModal.value = false;
              reload();
            }
          });
        }
      } else {
        Message.warning('请选择要发货的商品');
      }
    }
  };
  // 调整价格
  const modifyPrice = () => {
    adjustmentPrice.value = true;
    if (!orderInfo.value.order.flowPrice) return;
    modifyPriceForm.value.price = orderInfo.value.order.flowPrice;
  };
  // 调整价格确定按钮
  const modifyPriceSubmit = async () => {
    const res = await updateOrderPrice(route.query.id, {
      orderPrice: modifyPriceForm.value.price,
    });
    if (res.data.code == 200) {
      Message.success('修改订单金额成功');
      adjustmentPrice.value = false;
      init();
    }
  };
  // 返回
  const back = () => {
    router.push({ name: 'order-list' });
  };
  // 初始化
  onMounted(() => {
    init();
    getPackage(route.query.id).then((res: any) => {
      logisticsList.value = res.data.result;
    });
    getTraces(route.query.id).then((res) => {
      if (res.data.success && res.data.result != null) {
        logisticsInfo.value = res.data.result;
      }
    });
    getLogisticsChecked().then((res) => {
      if (res.data.success) {
        checkedLogistics.value = res.data.result;
      }
    });
  });
</script>

<style lang="less" scoped>
  .wuliu {
    .layui-layer-wrap {
      .flex {
        height: 32px;
        color: #333333;
        line-height: 32px;
        > div:nth-of-type(1) {
          width: 80px;
        }
      }
      > .div-express-log {
        max-height: 300px;
      }
      :deep(.div-express-log::-webkit-scrollbar){
        width: 1px;
        height: 5px;
      }
      :deep(.div-express-log::-webkit-scrollbar-thumb){
        border-radius: 1em;
        background-color: rgba(50,50,50,.3);
      }
      :deep(.div-express-log::-webkit-scrollbar-track){
        border-radius: 1em;
        background-color: rgba(50,50,50,.1);
      }
    }
    .div-express-log {
      border: solid 1px #e7e7e7;
      background: #fafafa;
      overflow-y: auto;
      overflow-x: auto;
    }
    .express-log {
      padding: 0 10px;
      list-style-type: none;
      .time {
        width: 30%;
        display: inline-block;
      }
      .detail {
        width: 60%;
        margin-left: 30px;
        display: inline-block;
      }
      li {
        line-height: 30px;
      }
    }
    .express-log-name {
      li {
        display: flex;
        span  {
          display: flex;
        }
      }
    }
  }

  :deep(.arco-card-header) {
    border-bottom: none !important;
  }
  .arco-card {
    margin: 20px 0;
    padding: 20px;
  }
  .grid-row {
    margin: 0 0 15px 40px;
    span {
      color: #000;
    }
  }
  .footer {
    padding: 20px;
    height: 150px;
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
    div {
      margin-left: 15px;
      color: #999;
    }
    .footer-font {
      font-size: 16px;
      color: #000;
      margin-top: -2px;
      span {
        color: #165dff;
      }
    }
  }

  .printgoodtitle {
    font-size: 14px;
    line-height: 1.5;
    margin-top: 15px;
    color: #333;
  }

  .printgoodinfo {
    padding: 10px;
    overflow: hidden;
    color: #333;

    .printgooditem {
      border-bottom: 1px solid #e8eaec;
      display: flex;
      align-items: flex-start;
      overflow: hidden;
      line-height: 30px;
      margin-bottom: 10px;
      padding-bottom: 10px;

      .printgoodname {
        flex: 1;
        overflow: hidden;

        .printgoodguid {
          font-size: 12px;
          color: #999999;
          line-height: 1.5;

          .printgoodguiditem {
            margin-right: 10px;
          }
        }
      }

      .printgoodprice {
        width: 135px;
        margin-left: 15px;
      }

      .printgoodnumber {
        width: 85px;
        margin-left: 15px;
      }
    }
  }
  .print-good-title {
    font-size: 14px;
    line-height: 1.5;
    margin-top: 15px;
    margin-bottom: 15px;
    color: #000;
  }
  .printFooter {
    position: absolute;
    bottom: 0px;
    width: 100%;
    p {
      text-align: center;
    }
  }
  @media print {
    @page {
      size: auto;
      margin: 3mm;
    }

    html,
    body {
      height: inherit;
    }
  }
</style>
